<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="$emit('returnModify')"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-supplierName>
                <el-input
                  v-model="formInfo.data.supplierName"
                  class="not-mongolia"
                  type="input"
                  placeholder="请选择供应商"
                  :disabled="true"
                >
                  <template #append>
                    <el-icon @click="selectSupplier"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-orderDate="scope">
                <el-date-picker
                  v-model="formInfo.data.orderDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                />
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addProduct>
                <el-button :disabled="!canAddProduct" @click="addProduct"
                  >添加发票</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                  >删除发票</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  class="table-scroll-hidden"
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="false"
                  :query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetApplicationNo="scope">
                    <span
                      class="slip-edit"
                      @click="showAssetApplicationDetail(scope.row)"
                      >{{ scope.row.assetApplicationNo }}</span
                    >
                  </template>
                  <!-- 付款金额小于 可付款金额 -->
                  <template v-slot:col-paymentAmount="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.paymentAmount`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positive,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.paymentAmount"
                        clearable
                        controls-position="right"
                        :precision="systemConfig.qty_show_precision"
                        :min="0"
                        :max="scope.row.balanceAmount || 99999"
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!--资产选择-->
    <SelectToInvoice
      v-if="selectEquipmentInfo.visible"
      v-model:show-dialog="selectEquipmentInfo.visible"
      :query="selectEquipmentInfo.query.queryMap"
      :query-params="selectEquipmentInfo.query.queryParams"
      :tableKey="selectEquipmentInfo.tableKey"
      :api="selectEquipmentInfo.api"
      :check-box="true"
      @callback="callBackEquipment"
    />

    <SelectSupplier
      v-if="supplierInfo.visible"
      v-model:show-dialog="supplierInfo.visible"
      :query="supplierInfo.query"
      :check-box="false"
      :highlight-row="true"
      :api="supplierInfo.api"
      @callback="selectSupplierCallback"
    />
  </div>
</template>

<script setup name="paymentModify">
import {
  getPurchInvoiceOrderCustomizeListPage,
  createPaymentOrder,
  createPaymentOrderAndSave,
  submitPaymentOrder,
  createPaymentOrderFlowSaveAndSubmit,
  updatePaymentOrder,
  getPaymentOrderOrderById,
  getPaymentOrderDetailCustomizeListAll,
} from '@/api/asset.js'
import moment from 'moment'
import { getSupplierPage } from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps([
  'tableKey',
  'visible',
  'title',
  'orderId',
  'tableData',
  'id',
  'flowFormType',
])
const supplierInfo = ref({
  visible: false,
  query: {
    id: '',
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
  api: getSupplierPage,
})
const formRefs = ref([])
const formInfo = ref({
  ref: null,
  data: {
    supplierId: '',
    supplierName: '',
    orderDate: moment(new Date()).format('YYYY-MM-DD'),
  },
  fieldList: [
    { label: '单据日期', value: 'orderDate', type: 'slot' },
    { label: '供应商', value: 'supplierName', type: 'slot' },
    { label: '付款金额', value: 'sumAmount', type: 'input', disabled: true },
    {
      label: '供应商总金额',
      value: 'supplierSumAmount',
      type: 'input',
      disabled: true,
    },
    {
      label: '供应商总余额',
      value: 'supplierBalanceAmount',
      type: 'input',
      disabled: true,
    },
    { label: '合同编码', value: 'contractNo', type: 'input' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  // invoiceAmount 开票金额
  // balanceAmount 可付款金额
  // paymentAmount 付款金额

  rules: {
    orderDate: [
      { required: true, message: '请选择单据日期', trigger: 'change' },
    ],
    supplierName: [
      { required: true, message: '请选择供应商', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      // needPendPurchQty: true,
    },
  },
  list: [
    { type: 'slot', label: '添加产品', value: 'addProduct' },
    { type: 'slot', label: '删除产品', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  summaryFieldList: [
    { value: 'paymentAmount', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  applicationFieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const fullInfo = ref({
  btnList: [
    {
      label: '保存并提交',
      event: saveAndSubmit,
      show:
        !props.orderId &&
        !props.id &&
        proxy.$permission('assetPaymentOrder:saveAndSubmit') &&
        !props.flowFormType,
    },
    { label: '保存', event: save, show: !props.flowFormType },
  ],
})
const selectEquipmentInfo = ref({
  visible: false,
  tableKey:
    'assetPurchInvoiceOrderList-com.slip.spd.entity.vo.asset.AssetPurchInvoiceOrderVO',
  api: getPurchInvoiceOrderCustomizeListPage,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      supplierId: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '4',
      },
    },
    queryParams: {
      isPay: 1,
    },
  },
})

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const licencesSystemConfig = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canAddProduct = computed(() => {
  return formInfo.value.data.supplierId
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

watch(
  () => tableInfo.value.data,
  () => {
    formInfo.value.data.sumAmount = 0
    formInfo.value.data.supplierSumAmount = 0
    formInfo.value.data.supplierBalanceAmount = 0
      // invoiceAmount 开票金额
  // balanceAmount 可付款金额
  // paymentAmount 付款金额
    tableInfo.value.data.forEach((row) => {
      formInfo.value.data.sumAmount += row.paymentAmount || 0
      formInfo.value.data.supplierSumAmount += row.invoiceAmount || 0
      formInfo.value.data.supplierBalanceAmount += row.balanceAmount || 0
    })
    formInfo.value.data.supplierBalanceAmount = formInfo.value.data.supplierBalanceAmount - formInfo.value.data.sumAmount
    // formInfo.value.data.supplierBalanceAmount =
    //   formInfo.value.data.supplierSumAmount - formInfo.value.data.sumAmount
  },
  {
    deep: true,
  }
)

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
})
onUnmounted(() => {
  sessionStorage.removeItem('payentData')
})


setData()
function setData() {
  let obj = {
    paymentAmount: {
      label: '付款金额',
      value: 'paymentAmount',
      type: 'slot',
      minWidth: '150px',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}

function selectSupplier() {
  // 供应商
  supplierInfo.value.visible = true
}

function selectSupplierCallback(data) {
  if (data.supplierId !== formInfo.value.data.supplierId) {
    formInfo.value.data.supplierId = data.supplierId
    formInfo.value.data.supplierName = data.supplierName
    selectEquipmentInfo.value.query.queryMap.supplierId.value = data.supplierId
    tableInfo.value.data = []
  }
}

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//添加产品按钮
function addProduct() {
  if (tableInfo.value.data.length) {
    selectEquipmentInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.invoiceOrderId)
      .toString()
  } else {
    selectEquipmentInfo.value.query.queryMap.id.value = ''
  }
  if (props.id || props.orderId) {
    selectEquipmentInfo.value.query.queryParams['orderIdNotEqual'] =
      formInfo.value.data.id
  }
  selectEquipmentInfo.value.visible = true
}

function callBackEquipment(rows) {
  // 这里前端作缓存 因为可付款金额有问题 删除之后和重新选择不一样 见id 10760
  if (rows && rows.length) {
    let payentData = JSON.parse(sessionStorage.getItem('payentData'))
    if(payentData && payentData.length) {
      rows.map(item => {
        payentData.map(i => {
          if(i.invoiceOrderNo == item.orderNo) {
            item.availableSumAmount = i.balanceAmount
          }
        })
      })
    }
    const data = rows.map(function (item) {
      let id = item.id
      delete item.id
      return {
        ...item,
        invoiceOrderNo: item.orderNo,
        invoiceAmount: item.sumAmount,
        balanceAmount: item.availableSumAmount,
        invoiceOrderId: id,
      }
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
//删除产品
function removeProduct(row = undefined) {
  if (row.uuid && row) {
    tableInfo.value.data = tableInfo.value.data.filter((item) => row !== item)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function showAssetApplicationDetail(row) {
  assetApplicationDetailInfo.value.id = row.assetApplicationId
  assetApplicationDetailInfo.value.visible = true
}
// flowData 外部流程页面调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.value.data.map((item) => {
      return {
        ...item,
        calcQty: item.qty,
      }
    })
    let commonName = details
      .filter((item) => !item.supplierId)
      .map((item) => item.commonName)
    if (commonName.length > 0) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: `产品${commonName}供应商不能为空!`,
      })
    } else {
      const data = formInfo.value.data
      data.mergeDetails = details
      if (data.mergeDetails.length === 0) {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: '产品不能为空',
        })
        return
      }
      let api = data.id
        ? updatePaymentOrder
        : isSaveAndSubmit === true
        ? createPaymentOrderAndSave
        : createPaymentOrder
      let flowParams = data
      if (isSaveAndSubmit === true) {
        flowParams = {
          orderData: data,
          // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
          flowTaskCommentDto: { approvalType: 'submit' },
          processDefinitionKey: 'payment',
          processInstanceId: obj.processInstanceId,
          taskId: obj.taskId,
        }
        if (proxy.$route.query.processInstanceId) {
          api = submitPaymentOrder
        }
      }
      api(flowParams).then((resp) => {
        if (resp && resp.success) {
          emits('returnModify', false)
          showDialog.value = false
        }
      })
    }
  })
}
function _getAssetPurchOrderById(orderId) {
  getPaymentOrderOrderById(orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      selectEquipmentInfo.value.query.queryMap.supplierId.value =
        resp.data.supplierId + ''
      getAssetPurchOrderDetails()
    }
  })
}
function getAssetPurchOrderDetails() {
  getPaymentOrderDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      let data = JSON.parse(JSON.stringify(resp.data))
      data.forEach((item) => {
        item.supplierId = formInfo.value.data.supplierId
        item.supplierName = formInfo.value.data.supplierName
        item.balanceAmount = item.balanceAmount + item.paymentAmount
      })
      tableInfo.value.data = data
      // 缓存已经添加发票
      sessionStorage.setItem('payentData', JSON.stringify(data))
      console.log(tableInfo.value.data)
    }
  })
}

function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(licencesSystemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
function getCustomize() {
  let param = {
    tableKey:
      props.tableKey ||
      'assetPaymentOrderModify-com.slip.spd.entity.vo.asset.AssetPaymentOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      console.log(tableInfo.value.fieldList)

      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.id || props.orderId
      if (props.id || props.orderId) {
        _getAssetPurchOrderById(props.id || props.orderId)
      }
    }
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
.model-panel-title {
  display: flex;
  align-items: center;

  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;

    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }

    .model-tips-nearly {
      background: #fceacb;
    }

    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}

:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
}
</style>
